package org.example.service.impl;

import com.github.pagehelper.PageHelper;
import org.example.dao.ModelDao;
import org.example.dao.UserDao;
import org.example.domain.Model;
import org.example.domain.PageBean;
import org.example.domain.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jimmy
 * @version 1.0
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private ModelDao modelDao;


    @Override
    public User login(String email, String password) {
        User user = userDao.login(email, password);
        if (user != null){
            List<String> rids = userDao.findRid(user.getId());
            user.setRid(rids);
        }
        return user;
    }

    @Override
    public PageBean findByPage(User user, int pagenum, int pagesize) {
        int total = userDao.findTotal(user);
        if (total<pagesize){
            pagesize = total;
        }
        PageHelper.startPage(pagenum,pagesize);
        List<User> users = userDao.findByPage(user);

        PageBean pageBean = new PageBean(total,pagenum);
        pageBean.setUsers(users);
        return pageBean;

    }

    @Override
    public User findById(String id) {
        User user = userDao.findById(id);
        return user;
    }

    @Override
    public int update(User user) {
        int i = userDao.update(user);
        return i;
    }

    @Override
    public List<Model> userPower(List<String> rids) {
        List<Model> modelList = new ArrayList<>();
        for (String rid : rids) {
            List<String> modelIds = modelDao.findByRid(rid);
            for (String modelId : modelIds) {
                Model model = modelDao.findByMid(modelId);
                modelList.add(model);
            }
        }

        List<Model> modelParents = new ArrayList<>();
        for (Model model : modelList) {
            if (model.getPid() == null){
                modelParents.add(model);
            }
        }
        for (Model modelParent : modelParents) {
            List<Model> modelChild = new ArrayList<>();
            for (Model model : modelList) {
                if (modelParent.getModelId().equals(model.getPid())){
                    modelChild.add(model);
                }
            }
            modelParent.setChildren(modelChild);
        }

        return modelParents;
    }

    @Override
    public int delete(String id) {
        int i = userDao.delete(id);
        return i;
    }

    @Override
    public List<String> findRidById(String id) {
        List<String> rids = userDao.findRid(id);
        return rids;
    }


}
